/*
@file: CodeTip.cpp
@author: ZZH
@date: 2022-11-04
@info: 代码提示框
*/
#include "CodeTip.h"

CodeTip::CodeTip(QWidget* parent): QListWidget(parent)
{
    this->setBaseSize(30, 15);
    this->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
    this->setFocusPolicy(Qt::FocusPolicy::StrongFocus);
    this->setEditTriggers(EditTrigger::NoEditTriggers);
    this->hide();
}

void CodeTip::requestCodeTip(const QPoint& pos, const QString& keyWord)
{
    UI_INFO("show codeTip");
    if (keyWord.isEmpty())
        return;
    auto rect = this->geometry();
    rect.moveTopLeft(pos);
    this->setGeometry(rect);
    this->show();
    this->setFocus(Qt::FocusReason::PopupFocusReason);
    this->addItem("str1");
    this->addItem("str2");
    this->addItem("str3");
    this->setCurrentRow(0);
}

void CodeTip::focusOutEvent(QFocusEvent* e)
{
    QListWidget::focusOutEvent(e);
    this->hide();
    // this->releaseKeyboard();
    e->accept();
}

void CodeTip::keyPressEvent(QKeyEvent* e)
{
    UI_INFO("CodeTip key press");
    if (e->count() != 1)
        e->ignore();

    switch (e->key())
    {
        case Qt::Key_Tab://按下tab键
        case Qt::Key_Enter://按下enter键
        {
            e->accept();
            auto curItem = this->currentItem();

            if (nullptr != curItem)
                emit selectItemDone(curItem->text());

            this->clear();
        }
        break;

        case Qt::Key_Up:
        {
            auto row = this->currentRow();
            this->setCurrentRow(row > 0 ? row - 1 : 0);
        }
        break;

        case Qt::Key_Down:
        {
            auto row = this->currentRow();
            this->setCurrentRow(row < this->count() ? row + 1 : row);
        }
        break;

        default:
            UI_INFO("ignore this key");
            e->ignore();
            break;
    }
}
